package persistence

import (
	"context"

	"Data-API-MCP/backend/internal/domain/entity"
	"Data-API-MCP/backend/internal/domain/repository"
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

// PostgreSQLConnection PostgreSQL数据库连接实现
type PostgreSQLConnection struct {
	db   *sql.DB
	conn *entity.Connection
}

// NewPostgreSQLConnection 创建PostgreSQL连接
func NewPostgreSQLConnection(conn *entity.Connection) (repository.DBConnection, error) {
	db, err := sql.Open("postgres", conn.GetDSN())
	if err != nil {
		return nil, fmt.Errorf("创建PostgreSQL连接失败: %v", err)
	}

	// 设置连接池参数
	db.SetMaxIdleConns(conn.MaxIdleConns)
	db.SetMaxOpenConns(conn.MaxOpenConns)

	return &PostgreSQLConnection{
		db:   db,
		conn: conn,
	}, nil
}

// Execute 执行SQL查询
func (c *PostgreSQLConnection) Execute(ctx context.Context, query string, args ...interface{}) (interface{}, error) {
	rows, err := c.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	// 获取列信息
	columns, err := rows.Columns()
	if err != nil {
		return nil, err
	}

	// 准备结果集
	var result []map[string]interface{}
	for rows.Next() {
		// 创建一行数据
		row := make(map[string]interface{})
		values := make([]interface{}, len(columns))
		valuePtrs := make([]interface{}, len(columns))
		for i := range columns {
			valuePtrs[i] = &values[i]
		}

		// 扫描行数据
		if err := rows.Scan(valuePtrs...); err != nil {
			return nil, err
		}

		// 将数据转换为map
		for i, col := range columns {
			row[col] = values[i]
		}
		result = append(result, row)
	}

	return result, nil
}

// Close 关闭连接
func (c *PostgreSQLConnection) Close() error {
	return c.db.Close()
}

// Ping 测试连接
func (c *PostgreSQLConnection) Ping(ctx context.Context) error {
	return c.db.PingContext(ctx)
}

// GetConnectionInfo 获取连接信息
func (c *PostgreSQLConnection) GetConnectionInfo() *entity.Connection {
	return c.conn
}
